import { useState, useEffect } from 'react';
import { useLanguage } from '@kernelproxy/i18n';
import { useNavigate } from 'react-router-dom';
import { 
  MessageSquare, 
  Send, 
  AlertCircle,
  CheckCircle,
  Clock,
  Paperclip,
  Mail,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  Loader2
} from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { 
  ticketService, 
  type Ticket, 
  type TicketPriority, 
  type TicketCategory 
} from '../../services/ticket';

const Support = () => {
  const { language } = useLanguage();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [showForm, setShowForm] = useState(false);
  const [subject, setSubject] = useState('');
  const [category, setCategory] = useState<TicketCategory>('technical');
  const [priority, setPriority] = useState<TicketPriority>('medium');
  const [message, setMessage] = useState('');
  const [email, setEmail] = useState('');
  
  // Data state
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [totalTickets, setTotalTickets] = useState(0);
  const ticketsPerPage = 10;

  // Load tickets on mount and page change
  useEffect(() => {
    loadTickets();
  }, [currentPage]);

  // Set user email as default
  useEffect(() => {
    if (user?.email) {
      setEmail(user.email);
    }
  }, [user]);

  const loadTickets = async () => {
    if (!user) return;
    
    setLoading(true);
    setError(null);
    
    const result = await ticketService.getUserTickets(user.$id, currentPage, ticketsPerPage);
    
    if (result.success) {
      setTickets(result.tickets);
      setTotalTickets(result.total);
    } else {
      setError(language === 'zh-CN' ? '加载工单失败' : 'Failed to load tickets');
    }
    
    setLoading(false);
  };

  // Pagination calculations
  const totalPages = Math.ceil(totalTickets / ticketsPerPage);
  const startIndex = (currentPage - 1) * ticketsPerPage;
  const endIndex = startIndex + ticketsPerPage;

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const getCategoryLabel = (cat: TicketCategory) => {
    const categoryMap = {
      'technical': language === 'zh-CN' ? '技术支持' : 'Technical Support',
      'billing': language === 'zh-CN' ? '账单问题' : 'Billing',
      'account': language === 'zh-CN' ? '账户管理' : 'Account',
      'feature': language === 'zh-CN' ? '功能建议' : 'Feature Request',
      'other': language === 'zh-CN' ? '其他' : 'Other'
    };
    return categoryMap[cat];
  };

  const categories = [
    { value: 'technical' as TicketCategory, label: language === 'zh-CN' ? '技术支持' : 'Technical Support' },
    { value: 'billing' as TicketCategory, label: language === 'zh-CN' ? '账单问题' : 'Billing' },
    { value: 'account' as TicketCategory, label: language === 'zh-CN' ? '账户管理' : 'Account' },
    { value: 'feature' as TicketCategory, label: language === 'zh-CN' ? '功能建议' : 'Feature Request' },
    { value: 'other' as TicketCategory, label: language === 'zh-CN' ? '其他' : 'Other' }
  ];

  const priorities = [
    { value: 'low', label: language === 'zh-CN' ? '低' : 'Low', color: 'text-gray-600' },
    { value: 'medium', label: language === 'zh-CN' ? '中' : 'Medium', color: 'text-blue-600' },
    { value: 'high', label: language === 'zh-CN' ? '高' : 'High', color: 'text-orange-600' },
    { value: 'urgent', label: language === 'zh-CN' ? '紧急' : 'Urgent', color: 'text-red-600' }
  ];

  const getStatusBadge = (status: string) => {
    const badges = {
      'open': {
        bg: 'bg-blue-100 dark:bg-blue-900',
        text: 'text-blue-800 dark:text-blue-200',
        label: language === 'zh-CN' ? '待处理' : 'Open',
        icon: <AlertCircle size={14} />
      },
      'in-progress': {
        bg: 'bg-yellow-100 dark:bg-yellow-900',
        text: 'text-yellow-800 dark:text-yellow-200',
        label: language === 'zh-CN' ? '处理中' : 'In Progress',
        icon: <Clock size={14} />
      },
      'resolved': {
        bg: 'bg-green-100 dark:bg-green-900',
        text: 'text-green-800 dark:text-green-200',
        label: language === 'zh-CN' ? '已解决' : 'Resolved',
        icon: <CheckCircle size={14} />
      },
      'closed': {
        bg: 'bg-gray-100 dark:bg-gray-700',
        text: 'text-gray-800 dark:text-gray-200',
        label: language === 'zh-CN' ? '已关闭' : 'Closed',
        icon: <CheckCircle size={14} />
      }
    };
    return badges[status as keyof typeof badges];
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!user) return;
    
    setSubmitting(true);
    setError(null);
    
    const result = await ticketService.createTicket(
      {
        subject,
        category,
        priority,
        description: message,
        userEmail: email || user.email,
      },
      user.$id,
      user.name || user.email,
      user.email
    );
    
    if (result.success) {
      // Reset form
      setSubject('');
      setMessage('');
      setEmail('');
      setCategory('technical');
      setPriority('medium');
      setShowForm(false);
      
      // Reload tickets
      loadTickets();
    } else {
      setError(language === 'zh-CN' ? '创建工单失败，请重试' : 'Failed to create ticket, please try again');
    }
    
    setSubmitting(false);
  };

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
            <MessageSquare size={28} />
            {language === 'zh-CN' ? '技术支持' : 'Support Tickets'}
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            {language === 'zh-CN' ? '提交工单或查看现有工单状态' : 'Submit a ticket or view existing tickets'}
          </p>
        </div>
        <button
          onClick={() => navigate('/dashboard/support/create')}
          className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2"
        >
          <Send size={18} />
          {language === 'zh-CN' ? '创建工单' : 'New Ticket'}
        </button>
      </div>

      {/* New Ticket Form */}
      {showForm && (
        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '创建新工单' : 'Create New Ticket'}
          </h2>
          
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Email */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                <div className="flex items-center gap-2">
                  <Mail size={16} />
                  {language === 'zh-CN' ? '联系邮箱' : 'Email'}
                </div>
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                readOnly
                required
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 cursor-not-allowed"
                placeholder={language === 'zh-CN' ? '您的邮箱地址' : 'Your email address'}
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                {language === 'zh-CN' ? '使用您的账户邮箱' : 'Using your account email'}
              </p>
            </div>

            {/* Subject */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {language === 'zh-CN' ? '主题' : 'Subject'}
              </label>
              <input
                type="text"
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                required
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
                placeholder={language === 'zh-CN' ? '简要描述您的问题' : 'Brief description of your issue'}
              />
            </div>

            {/* Category and Priority */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '类别' : 'Category'}
                </label>
                <div className="relative">
                  <select
                    value={category}
                    onChange={(e) => setCategory(e.target.value as TicketCategory)}
                    className="w-full pl-4 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none cursor-pointer"
                  >
                    {categories.map(cat => (
                      <option key={cat.value} value={cat.value}>{cat.label}</option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500 pointer-events-none z-10" />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '优先级' : 'Priority'}
                </label>
                <div className="relative">
                  <select
                    value={priority}
                    onChange={(e) => setPriority(e.target.value as TicketPriority)}
                    className="w-full pl-4 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none cursor-pointer"
                  >
                    {priorities.map(pri => (
                      <option key={pri.value} value={pri.value}>{pri.label}</option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500 pointer-events-none z-10" />
                </div>
              </div>
            </div>

            {/* Message */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {language === 'zh-CN' ? '详细描述' : 'Description'}
              </label>
              <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                required
                rows={6}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
                placeholder={language === 'zh-CN' ? '请详细描述您遇到的问题...' : 'Please describe your issue in detail...'}
              />
            </div>

            {/* Attachment */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                <div className="flex items-center gap-2">
                  <Paperclip size={16} />
                  {language === 'zh-CN' ? '附件（可选）' : 'Attachments (Optional)'}
                </div>
              </label>
              <input
                type="file"
                multiple
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                {language === 'zh-CN' ? '支持的格式：图片、PDF、文本文件。最大 10MB' : 'Supported formats: Images, PDF, Text files. Max 10MB'}
              </p>
            </div>

            {/* Submit Buttons */}
            <div className="flex gap-3 pt-4">
              <button
                type="submit"
                disabled={submitting}
                className="flex-1 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                {submitting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {language === 'zh-CN' ? '提交中...' : 'Submitting...'}
                  </>
                ) : (
                  <>
                    <Send size={18} />
                    {language === 'zh-CN' ? '提交工单' : 'Submit Ticket'}
                  </>
                )}
              </button>
              <button
                type="button"
                onClick={() => setShowForm(false)}
                className="px-6 py-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 font-medium rounded-lg transition-colors"
              >
                {language === 'zh-CN' ? '取消' : 'Cancel'}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Existing Tickets */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '我的工单' : 'My Tickets'}
          </h2>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '工单ID' : 'Ticket ID'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '主题' : 'Subject'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '类别' : 'Category'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '优先级' : 'Priority'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '状态' : 'Status'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '最后更新' : 'Last Update'}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center">
                    <Loader2 className="w-8 h-8 animate-spin mx-auto text-gray-400" />
                    <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                      {language === 'zh-CN' ? '加载中...' : 'Loading...'}
                    </p>
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center">
                    <AlertCircle className="w-8 h-8 mx-auto text-red-400" />
                    <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>
                    <button
                      onClick={loadTickets}
                      className="mt-4 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                    >
                      {language === 'zh-CN' ? '重试' : 'Retry'}
                    </button>
                  </td>
                </tr>
              ) : tickets.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center">
                    <MessageSquare className="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600" />
                    <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
                      {language === 'zh-CN' ? '暂无工单' : 'No tickets yet'}
                    </p>
                  </td>
                </tr>
              ) : (
                tickets.map((ticket) => {
                  const statusBadge = getStatusBadge(ticket.status);
                  const priorityColor = priorities.find(p => p.value === ticket.priority)?.color || 'text-gray-600';
                  
                  return (
                    <tr key={ticket.$id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          onClick={() => navigate(`/dashboard/support/ticket/${ticket.$id}`)}
                          className="text-blue-600 dark:text-blue-400 hover:underline"
                        >
                          {ticket.$id.substring(0, 8).toUpperCase()}
                        </button>
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-900 dark:text-white">
                        {ticket.subject}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                        {getCategoryLabel(ticket.category)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`text-sm font-medium ${priorityColor}`}>
                          {priorities.find(p => p.value === ticket.priority)?.label}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${statusBadge.bg} ${statusBadge.text}`}>
                          {statusBadge.icon}
                          {statusBadge.label}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                        {new Date(ticket.$updatedAt).toLocaleString(language === 'zh-CN' ? 'zh-CN' : 'en-US')}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {!loading && totalPages > 1 && (
          <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' 
                ? `显示 ${startIndex + 1}-${Math.min(endIndex, totalTickets)} / 共 ${totalTickets} 个工单`
                : `Showing ${startIndex + 1}-${Math.min(endIndex, totalTickets)} of ${totalTickets} tickets`}
            </div>
            <div className="flex items-center space-x-2">
              <button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className="px-3 py-1.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                <button
                  key={page}
                  onClick={() => handlePageChange(page)}
                  className={`px-3 py-1.5 rounded-lg transition-colors ${
                    currentPage === page
                      ? 'bg-blue-600 text-white'
                      : 'border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                >
                  {page}
                </button>
              ))}

              <button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="px-3 py-1.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Help Section */}
      <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-6 border border-blue-200 dark:border-blue-800">
        <h3 className="text-lg font-semibold text-blue-900 dark:text-blue-100 mb-2">
          {language === 'zh-CN' ? '需要帮助？' : 'Need Help?'}
        </h3>
        <p className="text-sm text-blue-800 dark:text-blue-200 mb-4">
          {language === 'zh-CN' 
            ? '在提交工单之前，您可以查看我们的帮助文档或常见问题，可能会更快地找到答案。' 
            : 'Before submitting a ticket, check our documentation or FAQ for faster answers.'}
        </p>
        <div className="flex gap-3">
          <button className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm transition-colors">
            {language === 'zh-CN' ? '查看文档' : 'View Documentation'}
          </button>
          <button className="px-4 py-2 border border-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/40 text-blue-600 dark:text-blue-400 rounded-lg text-sm transition-colors">
            {language === 'zh-CN' ? '常见问题' : 'FAQ'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default Support;
